package com.example.servlet.servlet;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-01 11:43
 **/
@WebServlet("/demo/ServletDemo04")
public class ServletDemo4 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        if (!StringUtils.isNotBlank(filename)) {
            return;
        }
        //获取mimetype
        String mimeType = getServletContext().getMimeType(filename);
        System.out.println(filename + " 文件对应的mimeType: " + mimeType);
        resp.setHeader("Content-Type", mimeType);
        String realPath = getServletContext().getRealPath("/download/" + filename);
        System.out.println("真实路径: " + realPath);
        File file = new File(realPath);
        //设置文件名,记得要用ISO-8859-1,不然中文乱码
        resp.setHeader("Content-Disposition", "attachment;filename="
                + new String(filename.getBytes(), "ISO-8859-1"));
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {

            byte[] bytes = new byte[1024];
            int len;
            ServletOutputStream os = resp.getOutputStream();

            while ((len = bis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
